<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言承接上一篇，本篇主要想说明的有三部分：1、webpack构建bundle的原理分析；2、自定义loader；3、自定义plugin。 webpack打包原理webpack打包时，到底发生了怎样的过程呢？我们实现了一个webpack_require来实现自己的模块化，把代码都缓存在installedModules里面，代码文件以对象传递进来，key为路径，value为包裹的代码字符串，且代码内部">
<meta property="og:type" content="article">
<meta property="og:title" content="webpack原理分析">
<meta property="og:url" content="http://example.com/2021/04/02/webpack/webpack%E5%8E%9F%E7%90%86/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="前言承接上一篇，本篇主要想说明的有三部分：1、webpack构建bundle的原理分析；2、自定义loader；3、自定义plugin。 webpack打包原理webpack打包时，到底发生了怎样的过程呢？我们实现了一个webpack_require来实现自己的模块化，把代码都缓存在installedModules里面，代码文件以对象传递进来，key为路径，value为包裹的代码字符串，且代码内部">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/webpack%E5%8E%9F%E7%90%86.assets/16fa85e8e9265825">
<meta property="article:published_time" content="2021-04-02T04:18:39.000Z">
<meta property="article:modified_time" content="2021-11-03T08:22:52.740Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="webpack">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/webpack%E5%8E%9F%E7%90%86.assets/16fa85e8e9265825">

<link rel="canonical" href="http://example.com/2021/04/02/webpack/webpack%E5%8E%9F%E7%90%86/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>webpack原理分析 | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/04/02/webpack/webpack%E5%8E%9F%E7%90%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          webpack原理分析
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-04-02 12:18:39" itemprop="dateCreated datePublished" datetime="2021-04-02T12:18:39+08:00">2021-04-02</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:22:52" itemprop="dateModified" datetime="2021-11-03T16:22:52+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/webpack/" itemprop="url" rel="index"><span itemprop="name">webpack</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>承接上一篇，本篇主要想说明的有三部分：1、webpack构建bundle的原理分析；2、自定义loader；3、自定义plugin。</p>
<h1 id="webpack打包原理"><a href="#webpack打包原理" class="headerlink" title="webpack打包原理"></a>webpack打包原理</h1><p>webpack打包时，到底发生了怎样的过程呢？我们实现了一个<strong>webpack_require</strong>来实现自己的模块化，把代码都缓存在installedModules里面，代码文件以对象传递进来，key为路径，value为包裹的代码字符串，且代码内部的require都被替换成了webpack_require。其步骤如下：chunk为出口代码块、bundle为入口资源文件。</p>
<p>1、接受一份配置：webpack.config.js。</p>
<p>2、分析出入口模块的位置：读取入口模块的内容、分析内容；哪些是依赖，哪些是源码；对于ES6、JSX其他需要编译的要进行编译，让浏览器能够执行；分析其他模块。</p>
<p>3、生成对象结构的数据：包括模块路径、和已经处理好的内容。</p>
<p>4、创建bundle.js：启动器函数，来补充代码中可能出现的module、exports、require，从而让浏览器能够顺利地执行。</p>
<h2 id="执行流程"><a href="#执行流程" class="headerlink" title="执行流程"></a>执行流程</h2><p>1、将命令行参数与 <code>webpack 配置文件</code> 合并、解析得到参数对象。</p>
<p>2、参数对象传给 webpack 执行得到 <code>Compiler</code> 对象。</p>
<p>3、执行 <code>Compiler</code> 的 <code>run</code>方法开始编译。每次执行 <code>run</code> 编译都会生成一个 <code>Compilation</code> 对象。</p>
<p>4、触发 <code>Compiler</code> 的 <code>make</code>方法分析入口文件，调用 <code>compilation</code> 的 <code>buildModule</code> 方法创建主模块对象。</p>
<p>5、生成入口文件 <code>AST(抽象语法树)</code>，通过 <code>AST</code> 分析和递归加载依赖模块。</p>
<p>6、所有模块分析完成后，执行 <code>compilation</code> 的 <code>seal</code> 方法对每个 <code>chunk</code> 进行整理、优化、封装。</p>
<p>7、最后执行 <code>Compiler</code> 的 <code>emitAssets</code> 方法把生成的文件输出到 <code>output</code> 的目录中。</p>
<h2 id="simpleWebpack"><a href="#simpleWebpack" class="headerlink" title="simpleWebpack"></a>simpleWebpack</h2><p>bundle.js是webpack启动的入口，也是整个构建的入口。主要获取配置文件，并以此为参数构建webpack实例，从而开启打包进程。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//执行webpack构建的入口</span></span><br><span class="line"><span class="comment">//1.拿到webpack.config.js配置</span></span><br><span class="line"><span class="keyword">const</span> options = <span class="built_in">require</span>(<span class="string">"./webpack.config.js"</span>);</span><br><span class="line"><span class="keyword">const</span> webpack = <span class="built_in">require</span>(<span class="string">"./lib/webpack.js"</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> webpack(options).run();</span><br><span class="line"><span class="comment">//实例化一下webpack，并将配置传给它</span></span><br></pre></td></tr></table></figure>

<p>关键在于webpack.js，上面所说的三个步骤均在webpack.js中实现。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">"fs"</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">"path"</span>);</span><br><span class="line"><span class="keyword">const</span> parser = <span class="built_in">require</span>(<span class="string">"@babel/parser"</span>);<span class="comment">//用babel来分析哪些是JS代码，哪些是模块化的引入</span></span><br><span class="line"><span class="keyword">const</span> traverse = <span class="built_in">require</span>(<span class="string">"@babel/traverse"</span>).default;<span class="comment">//用该模块来实现遍历AST。</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> &#123; transformFromAst &#125; = <span class="built_in">require</span>(<span class="string">"@babel/core"</span>);<span class="comment">//使用其transformFromAst的API</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = <span class="class"><span class="keyword">class</span> <span class="title">webpack</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(options) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; entry, output &#125; = options;</span><br><span class="line">    <span class="keyword">this</span>.entry = entry;</span><br><span class="line">    <span class="keyword">this</span>.output = output;</span><br><span class="line">    <span class="keyword">this</span>.modules = [];</span><br><span class="line">  &#125; </span><br><span class="line">    <span class="comment">//定义一下启动函数run()</span></span><br><span class="line">  run() &#123;</span><br><span class="line">    <span class="comment">//开始分析入口模块的内容</span></span><br><span class="line">    <span class="keyword">const</span> info = <span class="keyword">this</span>.parse(<span class="keyword">this</span>.entry);</span><br><span class="line">    <span class="comment">//递归分析其他的模块 </span></span><br><span class="line">    <span class="comment">// console.log(info);</span></span><br><span class="line">    <span class="keyword">this</span>.modules.push(info);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="keyword">this</span>.modules.length; i++) &#123;</span><br><span class="line">      <span class="keyword">const</span> item = <span class="keyword">this</span>.modules[i];</span><br><span class="line">      <span class="keyword">const</span> &#123; dependencies &#125; = item;</span><br><span class="line">      <span class="keyword">if</span> (dependencies) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> j <span class="keyword">in</span> dependencies) &#123;</span><br><span class="line">          <span class="keyword">this</span>.modules.push(<span class="keyword">this</span>.parse(dependencies[j]));</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> obj = &#123;&#125;;</span><br><span class="line">    <span class="keyword">this</span>.modules.forEach(<span class="function">(<span class="params">item</span>) =&gt;</span> &#123;</span><br><span class="line">      obj[item.entryFile] = &#123;</span><br><span class="line">        dependencies: item.dependencies,</span><br><span class="line">        code: item.code,</span><br><span class="line">      &#125;;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="comment">// console.log(obj);</span></span><br><span class="line">    <span class="keyword">this</span>.file(obj);</span><br><span class="line">  &#125;</span><br><span class="line">  parse(entryFile) &#123;</span><br><span class="line">    <span class="comment">//利用node中的fs模块来分析入口文件 </span></span><br><span class="line">    <span class="keyword">const</span> content = fs.readFileSync(entryFile, <span class="string">"utf-8"</span>);</span><br><span class="line">    <span class="comment">//首先要区分获取的内容中，哪些是模块依赖，哪些是JS代码</span></span><br><span class="line">    <span class="comment">//利用babel来实现这种划分; @babel/parser</span></span><br><span class="line">    <span class="comment">//const parser = require("@babel/parser");  </span></span><br><span class="line">    <span class="keyword">const</span> ast = parser.parse(content, &#123;</span><br><span class="line">      sourceType: <span class="string">"module"</span>,</span><br><span class="line">    &#125;);<span class="comment">//会返回一个AST抽象语法树</span></span><br><span class="line">    <span class="keyword">const</span> dependencies = &#123;&#125;;</span><br><span class="line">      <span class="comment">//利用traverse来遍历AST语法树，并对模块化的做提取处理,返回该类型的结点</span></span><br><span class="line">    traverse(ast, &#123;</span><br><span class="line">      ImportDeclaration(&#123; node &#125;) &#123;</span><br><span class="line">        <span class="comment">//   "./a.js" =&gt; "./src/a.js" 拼接路径结构</span></span><br><span class="line">        <span class="keyword">const</span> newPathName =</span><br><span class="line">          <span class="string">"./"</span> + path.join(path.dirname(entryFile), node.source.value);</span><br><span class="line">        <span class="comment">// console.log(newPathName);处理好路径之后，存储在dependencies数组中</span></span><br><span class="line">        dependencies[node.source.value] = newPathName;</span><br><span class="line">      &#125;,</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">const</span> &#123; code &#125; = transformFromAst(ast, <span class="literal">null</span>, &#123;</span><br><span class="line">      presets: [<span class="string">"@babel/preset-env"</span>],<span class="comment">//利用babel来对内容进行处理</span></span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      entryFile,</span><br><span class="line">      dependencies,</span><br><span class="line">      code,</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  file(code) &#123;</span><br><span class="line">    <span class="comment">//创建自运行函数，处理require,module,exports</span></span><br><span class="line">    <span class="comment">//生成main.js = &gt;dist/main.js</span></span><br><span class="line">    <span class="keyword">const</span> filePath = path.join(<span class="keyword">this</span>.output.path, <span class="keyword">this</span>.output.filename);</span><br><span class="line">    <span class="built_in">console</span>.log(filePath);</span><br><span class="line">    <span class="comment">//require("./a.js")</span></span><br><span class="line">    <span class="comment">// this.entry = "./src/index.js"</span></span><br><span class="line">    <span class="keyword">const</span> newCode = <span class="built_in">JSON</span>.stringify(code);</span><br><span class="line">    <span class="keyword">const</span> bundle = <span class="string">`(function(graph)&#123;</span></span><br><span class="line"><span class="string">        function require(module)&#123;</span></span><br><span class="line"><span class="string">            function reRequire(relativePath)&#123;</span></span><br><span class="line"><span class="string">                return require(graph[module].dependencies[relativePath]) </span></span><br><span class="line"><span class="string">            &#125;</span></span><br><span class="line"><span class="string">            var exports = &#123;&#125;;</span></span><br><span class="line"><span class="string">            (function(require,exports,code)&#123;</span></span><br><span class="line"><span class="string">                eval(code)</span></span><br><span class="line"><span class="string">            &#125;)(reRequire,exports,graph[module].code)</span></span><br><span class="line"><span class="string">            return exports;</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string">        require('<span class="subst">$&#123;<span class="keyword">this</span>.entry&#125;</span>')</span></span><br><span class="line"><span class="string">    &#125;)(<span class="subst">$&#123;newCode&#125;</span>)`</span>;</span><br><span class="line">    fs.writeFileSync(filePath, bundle, <span class="string">"utf-8"</span>);<span class="comment">//把bundle中的内容写到main.js里面。</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="编写loader"><a href="#编写loader" class="headerlink" title="编写loader"></a>编写loader</h1><p>Loader的本质就是一个函数，声明式函数而不能用箭头函数；拿到源代码，再返回处理后的代码即可。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span> (<span class="params">source</span>) </span>&#123;</span><br><span class="line">  <span class="comment">//loader处理模块</span></span><br><span class="line">  <span class="comment">//多个loader是有顺序的 </span></span><br><span class="line">  <span class="comment">//一定要有返回值</span></span><br><span class="line">  <span class="comment">//   console.log(this, this.query, source);通过this、this.query来获取给loader传递的参数</span></span><br><span class="line">  <span class="comment">//   console.log(result);</span></span><br><span class="line">  <span class="keyword">const</span> callback = <span class="keyword">this</span>.async();</span><br><span class="line">  setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> result = source.replace(<span class="string">"hello"</span>, <span class="keyword">this</span>.query.name);</span><br><span class="line">    <span class="comment">// return result;</span></span><br><span class="line">    callback(<span class="literal">null</span>, result);</span><br><span class="line">  &#125;, <span class="number">3000</span>);</span><br><span class="line"></span><br><span class="line">  <span class="comment">//   return result;</span></span><br><span class="line">  <span class="comment">//this.callback(),返回多个信息</span></span><br><span class="line">  <span class="comment">//   this.callback(null, result);</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>在配置文件中使用loader时，要如何让loader接受参数：this.query、loader-utils。</p>
<p>this.callback：用于返回多个信息；this.async：如果loader里面有异步的消息需要去处理时，</p>
<p>当有多个loader时，会有执行顺序，自后往前、自下往上，</p>
<p>处理loader的路径问题，在配置文件中使用resolveLoader。</p>
<h1 id="编写Plugin"><a href="#编写Plugin" class="headerlink" title="编写Plugin"></a>编写Plugin</h1><p>Plugin：开始打包，在某个示刻，帮助我们处理一些事情的机制。Plugin要比loader稍微复杂一些，在webpack的源码中plugin的机制占据了很多的场景，可以说是webpack的灵魂。</p>
<p>Plugin的本质是一个类，里面包含一个apply函数，接受一个参数compiler。</p>
<p>设计模式包括：事件驱动、发布订阅。</p>
<p>webpack 就像一条生产线，要经过一系列处理流程后才能将源文件转换成输出结果。 这条生产线上的每个处理流程的职责都是单一的，多个流程之间有存在依赖关系，只有完成当前处理后才能交给下一个流程去处理。</p>
<p>插件就像是一个插入到生产线中的一个功能，在特定的时机对生产线上的资源做处理。webpack 通过 Tapable 来组织这条复杂的生产线。 webpack 在运行过程中会广播事件，插件只需要监听它所关心的事件，就能加入到这条生产线中，去改变生产线的运作。webpack 的事件流机制保证了插件的有序性，使得整个系统扩展性很好。</p>
<p>站在代码逻辑的角度就是：webpack 在编译代码过程中，会触发一系列 Tapable 钩子事件，插件所做的，就是找到相应的钩子，往上面挂上自己的任务，也就是注册事件，这样，当 webpack 构建的时候，插件注册的事件就会随着钩子的触发而执行了。其实跟vue的生命周期的执行方式本质上相差无几。</p>
<h2 id="plugin-的基本结构"><a href="#plugin-的基本结构" class="headerlink" title="plugin 的基本结构"></a>plugin 的基本结构</h2><p>一个 webpack plugin 由如下部分组成：</p>
<ol>
<li>一个命名的 Javascript 方法或者 JavaScript 类。</li>
<li>它的原型上需要定义一个叫做 <code>apply</code> 的方法。</li>
<li>注册一个事件钩子。</li>
<li>操作webpack内部实例特定数据。</li>
<li>功能完成后，调用webpack提供的回调。</li>
</ol>
<p>一个基本的 plugin 代码结构大致长这个样子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// plugins/MyPlugin.js</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyPlugin</span> </span>&#123;</span><br><span class="line">  apply(compiler) &#123;</span><br><span class="line">    compiler.hooks.done.tap(<span class="string">'My Plugin'</span>, (stats) =&gt; &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'Bravo!'</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = MyPlugin;</span><br></pre></td></tr></table></figure>

<p>这就是一个最简单的 webpack 插件了，它注册了 <code>Compiler</code> 上的异步串行钩子 <code>done</code>，在钩子中注入了一条控制台打印的语句。根据上文钩子的介绍我们可以知道，<code>done</code> 会在一次编译完成后执行。所以这个插件会在每次打包结束，向控制台首先输出这句 <code>Bravo!</code>。</p>
<p><img src="/webpack%E5%8E%9F%E7%90%86.assets/16fa85e8e9265825" alt="webpack-plugin1.jpg"></p>
<h2 id="开发一个文件清单插件"><a href="#开发一个文件清单插件" class="headerlink" title="开发一个文件清单插件"></a>开发一个文件清单插件</h2><p>我希望每次webpack打包后，自动产生一个打包文件清单，上面要记录文件名、文件数量等信息。</p>
<h3 id="思路："><a href="#思路：" class="headerlink" title="思路："></a>思路：</h3><ul>
<li>显然这个操作需要在文件生成到dist目录之前进行，所以我们要注册的是<code>Compiler</code>上的<code>emit</code>钩子。</li>
<li><code>emit</code> 是一个异步串行钩子，我们用 <code>tapAsync</code> 来注册。</li>
<li>在 <code>emit</code> 的回调函数里我们可以拿到 <code>compilation</code> 对象，所有待生成的文件都在它的 <code>assets</code> 属性上。</li>
<li>通过 <code>compilation.assets</code> 获取我们需要的文件信息，并将其整理为新的文件内容准备输出。</li>
<li>然后往 <code>compilation.assets</code> 添加这个新的文件。</li>
</ul>
<p>插件完成后，最后将写好的插件放到 webpack 配置中，这个包含文件清单的文件就会在每次打包的时候自动生成了。</p>
<h3 id="实现："><a href="#实现：" class="headerlink" title="实现："></a>实现：</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// plugins/FileListPlugin.js</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FileListPlugin</span> </span>&#123;</span><br><span class="line">    <span class="keyword">constructor</span> (options) &#123;</span><br><span class="line">    	<span class="comment">// 获取插件配置项</span></span><br><span class="line">        <span class="keyword">this</span>.filename = options &amp;&amp; options.filename ? options.filename : <span class="string">'FILELIST.md'</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    apply(compiler) &#123;</span><br><span class="line">        <span class="comment">// 注册 compiler 上的 emit 钩子</span></span><br><span class="line">        compiler.hooks.emit.tapAsync(<span class="string">'FileListPlugin'</span>, (compilation, cb) =&gt; &#123;</span><br><span class="line">            </span><br><span class="line">            <span class="comment">// 通过 compilation.assets 获取文件数量</span></span><br><span class="line">            <span class="keyword">let</span> len = <span class="built_in">Object</span>.keys(compilation.assets).length;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 添加统计信息</span></span><br><span class="line">            <span class="keyword">let</span> content = <span class="string">`# <span class="subst">$&#123;len&#125;</span> file<span class="subst">$&#123;len&gt;<span class="number">1</span>?<span class="string">'s'</span>:<span class="string">''</span>&#125;</span> emitted by webpack\n\n`</span>;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 通过 compilation.assets 获取文件名列表</span></span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">let</span> filename <span class="keyword">in</span> compilation.assets) &#123;</span><br><span class="line">                content += <span class="string">`- <span class="subst">$&#123;filename&#125;</span>\n`</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 往 compilation.assets 中添加清单文件</span></span><br><span class="line">            compilation.assets[<span class="keyword">this</span>.filename] = &#123;</span><br><span class="line">            	<span class="comment">// 写入新文件的内容</span></span><br><span class="line">                source: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">                    <span class="keyword">return</span> content;</span><br><span class="line">                &#125;,</span><br><span class="line">                <span class="comment">// 新文件大小（给 webapck 输出展示用）</span></span><br><span class="line">                size: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">                    <span class="keyword">return</span> content.length;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 执行回调，让 webpack 继续执行</span></span><br><span class="line">            cb();</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = FileListPlugin;</span><br></pre></td></tr></table></figure>
    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2021/04/02/webpack/webpack%E5%8E%9F%E7%90%86/" title="webpack原理分析">http://example.com/2021/04/02/webpack/webpack原理/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/webpack/" rel="tag"># webpack</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/03/27/webpack/webpack%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" rel="prev" title="webpack性能优化">
      <i class="fa fa-chevron-left"></i> webpack性能优化
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/05/10/react/react%E5%88%9D%E5%AD%A6/" rel="next" title="react初学">
      react初学 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#webpack打包原理"><span class="nav-number">2.</span> <span class="nav-text">webpack打包原理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#执行流程"><span class="nav-number">2.1.</span> <span class="nav-text">执行流程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#simpleWebpack"><span class="nav-number">2.2.</span> <span class="nav-text">simpleWebpack</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#编写loader"><span class="nav-number">3.</span> <span class="nav-text">编写loader</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#编写Plugin"><span class="nav-number">4.</span> <span class="nav-text">编写Plugin</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#plugin-的基本结构"><span class="nav-number">4.1.</span> <span class="nav-text">plugin 的基本结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开发一个文件清单插件"><span class="nav-number">4.2.</span> <span class="nav-text">开发一个文件清单插件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#思路："><span class="nav-number">4.2.1.</span> <span class="nav-text">思路：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实现："><span class="nav-number">4.2.2.</span> <span class="nav-text">实现：</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

